﻿using System;
using System.Data.Entity;
using System.Linq;

namespace NpCrm.DataAccess.Core
{
    public abstract class RepositoryBase<TEntity, TId> : IRepository<TEntity, TId> where TEntity : class 
    {
        private readonly NpCrmDataContext _context = new NpCrmDataContext();
        public NpCrmDataContext Context
        {
            get { return _context; }
        }

        private IDbSet<TEntity> _objectSet;
        internal IDbSet<TEntity> ObjectSet
        {
            get { return _objectSet ?? (_objectSet = _context.Set<TEntity>()); }
        }


        public virtual void Add(TEntity entity)
        {
            ObjectSet.Add(entity);
        }

        public virtual IQueryable<TEntity> All()
        {
            return ObjectSet.AsQueryable();
        }

        public virtual TEntity GetById(TId entityId)
        {
            return ObjectSet.Find(entityId);
        }

        public virtual void Delete(TEntity entity)
        {
            ObjectSet.Remove(entity);
        }

        public IQueryable<TEntity> Query(Func<TEntity, bool> expression)
        {
            return ObjectSet.Where(expression).AsQueryable();
        }

        public void Commit()
        {
            _context.SaveChanges();
        }

        public void Dispose()
        {
            if (_context != null)
                _context.Dispose();
        }
    }
}
